﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Genuilder.Extensibility;
using Genuilder.Extensibility.MSBuild;
using System.IO;

namespace Genuilder
{
	public class ExtensibilityFeature : Feature
	{
		string _TargetFile;
		public ExtensibilityFeature(string targetFile)
		{
			_TargetFile = targetFile;
		}
		public ExtensibilityFeature()
		{

		}
		public override void LoadFeature(Project project, MSBuildData msBuildData)
		{
			if(_Extensions.Count == 0)
				return;

			var targetFile = _TargetFile;
			if(targetFile == null)
			{
				targetFile = Path.Combine(project.CommonFeaturesPath, "Genuilder.Extensibility.targets");
				if(!File.Exists(targetFile))
				{
					throw new FileNotFoundException(Messages.TargetFileNotFoundForFeature(targetFile, "Genuilder.Extensibility"));
				}
			}

			new TargetFeature(targetFile).LoadFeature(project, msBuildData);
			var itemGroup = msBuildData.ProjectRootElement.AddItemGroup().After(msBuildData.StartImportGenuilder);
			var projDir = new FileInfo(project.Path).Directory.FullName;
			foreach(var extension in _Extensions)
			{
				itemGroup.AddItem("GenuilderExtension", extension.ToXmlValue(projDir))
					.AddMetadata("Visible", "false");
			}
		}


		List<IExtension> _Extensions = new List<IExtension>();
		public TExtension AddExtension<TExtension>(TExtension extension) where TExtension : IExtension
		{
			_Extensions.Add(extension);
			return extension;
		}

		public void AddExtensions(IEnumerable<IExtension> extensions)
		{
			foreach(var ex in extensions)
				AddExtension(ex);
		}
	}
}
